<?php
namespace app\common\model;

use think\facade\Cache;

class DictModel extends BaseModel
{
    protected $name = 'dict';
    protected $pk='id';
    //开启自动写入时间戳
    protected $autoWriteTimestamp = false;

    /**
     * 添加
     * @param $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addData($data) {
        $info = $this->where('class_code',$data['class_code'])->where('dict_code',$data['dict_code'])->find();
        if($info) exception("该分类下已存在{$data['dict_code']}编码");
        self::create($data);
        $this->updateCache();
    }
    /**
     * 编辑
     * @param $data
     */
    public function editData($data) {
        $info = $this->where('id',$data['id'])->find();
        if($info['dict_code']!=$data['dict_code'] && $this->where('class_code',$info['class_code'])->where('dict_code',$data['dict_code'])->find()){
            exception('单据编码已存在！',40001);
        }
        self::update($data);
        $this->updateCache();
    }

    /**
     * 删除
     * @param $data
     * @throws \Exception
     */
    public function delData($data) {
        $this->where('id','in',$data)->delete();
        $this->updateCache();
    }

    /**
     * 更新字典缓存
     */
    public function updateCache(){
        $dictList = $this->order('show_order asc')->select();
        $cache=[];
        foreach($dictList as $k=>$v){
            $cache[$v['class_code'].'-'.$v['dict_code']] = $v;
        }
        Cache::set('dict',$cache);
    }

}